<template>
  <div class="mid-box">
    <el-collapse-transition>
      <div v-show="btnGroup.search" class="main-box search-box">
        <el-form
          class="troila-form"
          ref="searchInfo"
          :model="searchObj"
          :inline="true"
          label-width="110px"
        >
          <el-form-item
            label="用户名"
            prop="loginName"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="全部"
              v-model="searchObj.loginName"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="所属机构"
            prop="organizationId"
            class="troila-select-inline"
          >
            <treebox
              v-setwidth
              id="treebox"
              :list="treeArr"
              v-model="searchObj.organizationId"
              placeholder="全部"
              input
              :disabled="disabled"
              :clear="!disabled"
              onlyone
              :option="{ key: 'id', label: 'organizationName' }"
            ></treebox>
          </el-form-item>
          <el-form-item
            label="姓名"
            prop="userName"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="全部"
              v-model="searchObj.userName"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="手机号码"
            prop="phone"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="全部"
              v-model="searchObj.phone"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="角色"
            prop="roleIdStr"
            class="troila-select-inline"
          >
            <el-select
              v-setwidth
              placeholder="全部"
              v-model="searchObj.roleIdStr"
              clearable
              popper-class="troila-popper"
            >
              <el-option
                v-for="(item, index) in dictionary.roleList"
                :key="index"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="用户状态"
            prop="status"
            class="troila-select-inline"
          >
            <el-select
              v-setwidth
              placeholder="全部"
              v-model="searchObj.status"
              clearable
              popper-class="troila-popper"
            >
              <el-option
                v-for="(item, index) in userList"
                :key="index"
                :label="item.dictName"
                :value="item.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="添加日期" class="troila-select-inline">
            <el-date-picker
              v-model="createTime"
              v-setwidth
              placeholder="全部"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              type="daterange"
              popper-class="troila-popper"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="最后登录日期" class="troila-select-inline">
            <el-date-picker
              v-model="loginTime"
              v-setwidth
              placeholder="全部"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              type="daterange"
              popper-class="troila-popper"
            ></el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="登录名称"
                        prop="loginName"
                        class="troila-select-inline">
                        <el-input v-setwidth
                            placeholder="请输入登录名称"
                            v-model="searchObj.loginName"
                            clearable></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱账号"
                        prop="email"
                        class="troila-select-inline">
                        <el-input v-setwidth
                            placeholder="请输入邮箱账号"
                            v-model="searchObj.email"
                            clearable></el-input>
                    </el-form-item>

                    <el-form-item label="创建时间"
                        class="troila-select-inline">
                        <el-date-picker v-model="time"
                            v-setwidth
                            placeholder="全部"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd"
                            @change="changeDate"
                            type="daterange"
                            popper-class="troila-popper"></el-date-picker>
                    </el-form-item> -->
          <!-- <el-form-item class="searchBtn">
          </el-form-item> -->
        </el-form>
      </div>
    </el-collapse-transition>
    <!-- <div class="troila-group">
      <select-group
        v-model="btnGroup"
        :row="allTitle"
        :row-choose="chooseTitle"
        @rowChange="
          (arr) => {
            chooseTitle = arr
          }
        "
        @refresh="getList"
      />
    </div> -->
    <div class="main-box table-box">
      <div class="table-box-title ClearFloat">
        <!-- <i class="title-font">查询结果</i> -->
        <div class="troila-form">
          <el-button @click="submitSearch"
            ><unit-icon class="troila-icon" type="search" />查询</el-button
          >
          <el-button @click="resetForm"
            ><unit-icon class="troila-icon" type="refresh" />重置</el-button
          >
          <el-button v-limit="`system:userManage:add`" @click="btnClick('add')"
            ><unit-icon class="troila-icon" type="addLine" />添加</el-button
          >
          <el-button
            v-limit="`system:userManage:template`"
            @click="downloadExcel"
            ><unit-icon
              class="troila-icon"
              type="templates"
            />模板下载</el-button
          >
          <el-upload
            class="upload"
            action="1"
            :before-upload="beforeUploadFile"
            :http-request="uploadFile"
            :show-file-list="false"
          >
            <el-button v-limit="`system:userManage:import`"
              ><unit-icon class="troila-icon" type="import" />导入</el-button
            >
          </el-upload>
          <el-button v-limit="`system:userManage:export`" @click="exportUser"
            ><unit-icon class="troila-icon" type="export" />导出</el-button
          >
          <transtion-width>
            <span v-show="selection && selection.length > 0">
              <el-button
                v-limit="`system:userManage:batchStart`"
                @click="btnClick('batchStart')"
                ><unit-icon class="troila-icon" type="start" />启用</el-button
              >
              <el-button
                v-limit="`system:userManage:batchStop`"
                @click="btnClick('batchStop')"
                ><unit-icon class="troila-icon" type="stop" />禁用</el-button
              >
              <!-- <el-button  @click="btnClick('batchDelete')"
            >删除</el-button
          > -->
              <!-- v-limit="`system:userManage:batchDelete`" -->
              <el-button @click="btnClick('role')"
                ><unit-icon
                  class="troila-icon"
                  type="role"
                />角色授权</el-button
              >
              <!-- v-limit="`system:userManage:role`" -->
            </span>
          </transtion-width>
        </div>
      </div>
      <unit-table
        v-if="!btnGroup.card"
        selection
        :loading="loading"
        :title="tableTitle"
        :data="tableData"
        :opera="4"
        :operation="tableOperation"
        :dictionary="dictionary"
        @return="tableReturn"
        :page="pager.page"
      />
      <!-- <unit-cards
        v-if="btnGroup.card"
        selection
        :loading="loading"
        :title="tableTitle"
        :data="tableData"
        :opera="4"
        :operation="tableOperation"
        :dictionary="dictionary"
        @return="tableReturn"
        :page="pager.page"
      /> -->
      <pagination
        v-show="pager.total > pager.size"
        :pager="pager"
        @query="getList"
        ref="Pagerpagination"
      ></pagination>
    </div>
    <!-- <dialog-form v-model="showForm" @formConfirm="formConfirm" ref="userForm" /> -->
    <dialog-role v-model="showRole" @roleConfirm="roleConfirm" ref="userRole" />
  </div>
</template>
<script>
// import dialogForm from './dialog/userForm'
import dialogRole from './dialog/userRole'
import { downloadFile } from '@/assets/js/utils'
import { grobalbaseUrl } from '@/https/api/baseUrl'
export default {
  name: 'userManage',
  components: {
    // dialogForm,
    dialogRole,
  },
  data() {
    return {
      searchObj: {
        loginName: '',
        organizationId: '',
        userName: '',
        phone: '',
        roleIdStr: '',
        status: '',
        dateBegin: '',
        dateEnd: '',
        logdateBegin: '',
        logdateEnd: '',
      }, //搜索参数
      searchRes: {}, //搜索储存值
      loading: false,
      time: null, //时间组件值
      btnGroup: {
        //按钮组
        search: true,
        refresh: false,
        card: false,
      },
      pager: {
        // 页码
        total: 0,
        page: 1, //当前第几页
        size: 10, //每页显示的条数
      },
      dictionary: {
        // 字典信息
        // sex: [
        //   { dictName: '男', dictCode: '1' },
        //   { dictName: '女', dictCode: '0' },
        // ],
        // status: [
        // { dictName: '启用', dictCode: '1' },
        // { dictName: '禁用', dictCode: '0' },
        // ],
        roleList: [
          { roleName: '角色1', id: '1' },
          { roleName: '角色2', id: '2' },
          { roleName: '角色3', id: '3' },
          { roleName: '角色4', id: '4' },
          { roleName: '角色5', id: '5' },
        ],
      },
      allTitle: [
        // 全部可显示表头
        {
          label: '用户名', //*表头名称
          code: 'loginName', //*对应数据项
          tooltip: true, //超出显示浮层
          width: 110, //最小宽
        },
        {
          label: '所属机构',
          code: 'organization',
          tooltip: true,
          width: 140,
          format: (item, key) => {
            return this.judgeEmpty(item[key] ? item[key].organizationName : '')
          },
        },
        {
          label: '姓名',
          code: 'userName',
          tooltip: true,
          width: 110,
        },
        {
          label: '手机号码',
          code: 'phone',
          width: 110,
          tooltip: true,
        },
        {
          label: '邮箱账号',
          code: 'email',
          tooltip: true,
          width: 110,
        },
        {
          label: '性别',
          code: 'sex',
          dict: 'sex', //需要查询字典对应的key
          width: 60,
        },
        {
          label: '添加时间',
          code: 'createTime',
          tooltip: true,
          width: 110,
          format: (item, key) => {
            return this.toTime(item[key])
          },
        },
        {
          label: '创建人',
          code: 'createBy',
          tooltip: true,
          width: 110,
        },
        {
          label: '最后登录时间',
          code: 'loginTime',
          tooltip: true,
          width: 110,
          format: (item, key) => {
            return this.toTime(item[key])
          },
        },
        {
          label: '用户状态',
          code: 'status',
          dict: 'status',
          style: {
            //该项style
            color: [
              { value: '#f54141', result: 0 },
              { value: '#00c533', result: 1 },
            ],
          },
        },
      ],
      chooseTitle: [
        //被选中显示表头
        'loginName',
        'organization',
        'userName',
        'phone',
        'email',
        'createTime',
        'loginTime',
        'status',
      ],
      tableData: [],
      tableOperation: [
        //表格操作
        // *code 对应图标, label 对应浮层显示文字, show 判断是否显示, color 图标颜色
        { code: 'edit', limit: 'system:userManage:edit' },
        {
          code: 'user',
          label: '角色授权',
          limit: 'system:userManage:user',
        },
        {
          code: 'refresh',
          label: '重置密码',
          limit: 'system:userManage:resize',
        },
        {
          code: 'start',
          label: '启用',
          limit: 'system:userManage:start',
          show: (row) => {
            return row.status == 0
          },
        },
        {
          code: 'stop',
          label: '禁用',
          limit: 'system:userManage:stop',
          //   color: '#D13633',
          show: (row) => {
            return row.status == 1
          },
        },
        // {
        //   code: 'delete',
        //   //   limit: 'system:userManage:delete',
        // },
      ],
      selection: [], //表格选中行
      // showForm: false, //弹窗显示-新建修改
      showRole: false, //弹窗显示-分配角色
      editId: '',
      userId: '',
      disabled: false,
      treeArr: [],
      createTime: null,
      loginTime: null,
    }
  },
  computed: {
    tableTitle() {
      //表格表头
      return this.allTitle.filter(
        (item) => this.chooseTitle.indexOf(item.code) > -1
      )
    },
    userList() {
      let list = this.$store.state.dictionary.base_status
      this.dictionary.status = list
      let list1 = this.$store.state.dictionary.user_sex
      if (!list1) {
        this.$store.dispatch('dictionary/getDict', 'user_sex')
      }
      this.dictionary.sex = list1
      return list ? list : []
    },
  },
  methods: {
    // 获取列表
    getList() {
      let param = {
        pageNum: this.pager.page, //当前页
        pageSize: this.pager.size, //每页多少条
        ...this.searchRes,
      }
      this.loading = true
      setTimeout(() => {
        this.loading = false
        this.pager.total = 4
        this.tableData = [{}, {}, {}, {}]
      }, 100)
      return
      this.API.userManage
        .pageList(param)
        .then((res) => {
          // console.log(res)
          if (res.code === 1) {
            this.loading = false
            this.pager.total = res.data.total ? res.data.total : 0
            this.tableData = res.data.records
          } else {
            this.loading = false
          }
        })
        .catch((e) => {
          // console.log(e)
          this.loading = false
        })
    },

    // 重置
    resetForm() {
      // this.searchObj = {}
      this.$refs.searchInfo.resetFields()
      this.searchObj.dateBegin = ''
      this.searchObj.dateEnd = ''
      this.searchObj.logdateBegin = ''
      this.searchObj.logdateEnd = ''
      this.createTime = []
      this.loginTime = []
      this.searchRes = {}
      this.pager.page = 1
      this.getList()
    },
    // 搜索
    submitSearch() {
      this.searchRes = {
        ...this.searchObj,
        dateBegin:
          this.createTime && this.createTime.length > 0
            ? this.createTime[0]
            : '',
        dateEnd:
          this.createTime && this.createTime.length > 0
            ? this.createTime[1]
            : '',
        logdateBegin:
          this.loginTime && this.loginTime.length > 0 ? this.loginTime[0] : '',
        logdateEnd:
          this.loginTime && this.loginTime.length > 0 ? this.loginTime[1] : '',
      }
      this.pager.page = 1
      this.getList()
    },
    filteIds() {
      let arr = []
      if (this.dictionary.roleList && this.dictionary.roleList.length > 0) {
        arr = this.dictionary.roleList.map((v) => v.id)
      }
      return arr
    },
    // 按钮操作
    btnClick(method) {
      // console.log(method)
      let text = ''
      switch (method) {
        case 'add':
          // this.showForm = true
          // this.editId = ''
          this.$router.push({
            name: 'addUser',
          })
          return
        case 'batchStart':
          text = '启用'
          break
        case 'batchStop':
          text = '禁用'
          break
        case 'role':
          let filteIds = this.filteIds()
          console.log(filteIds)
          let arr = this.selection
            .filter(
              (v) =>
                v.roles &&
                v.roles.length > 0 &&
                v.roles.filter((v) => filteIds.indexOf(v.id) > -1).length > 0
            )
            .map((v) => `${v.userName}(${v.loginName})`)
          console.log(arr)
          if (arr.length > 0) {
            this.$confirmFn(
              `以下所选用户已有角色授权，不可以进行批量角色授权 ！<div>${arr.join(
                '、'
              )}</div>`,
              '提示',
              {
                confirmButtonText: '关闭',
                showCancelButton: false,
              }
            )
            return
          } else {
            this.showRole = {
              loginName: '',
              userName: this.selection
                .map((v) => `${v.userName}(${v.loginName})`)
                .join('、'),
              roleId: [],
            }
            this.userId = this.selection
          }
          return
        default:
          return
      }
      let name = this.selection.map((v) => `${v.userName}(${v.loginName})`)
      this.selection.length > 0
        ? this.$confirmFn(
            `您确定${text}以下用户吗？<div>${name.join('、')}</div>`,
            '提示',
            {
              callback: (action, instance) => {
                // console.log(action, instance)
                if (action == 'cancel ') {
                  return
                } else if (action == 'confirm') {
                  // console.log(this.selection)
                  let idList = this.selection.map((v) => v.id).join(',')
                  // console.log(idList, this.selection)
                  this.updateStatus({
                    ids: idList,
                    status: text === '启用' ? '1' : '0',
                  })
                }
              },
            }
          )
        : this.$alertFn.error(`请选择需要${text}的数据 ！`)
    },
    // 表格操作
    tableReturn(method, { row, prop, order, selection }) {
      // console.log(method, row, prop, order, selection)
      let text = '',
        text_ = ''
      switch (method) {
        case 'edit':
          // this.showForm = row
          // this.editId = row.id
          this.$router.push({
            name: 'editUser',
            params: { userId: this.encode(row.id), row: row },
          })
          return
        case 'user':
          this.showRole = row
          this.userId = row.id
          return
        case 'refresh':
          this.$confirmFn(
            `您确定为<span class='light'>${row.userName}(${row.loginName})</span>重置密码吗？`,
            '提示',
            {
              callback: (action, instance) => {
                // console.log(method, row)
                if (action == 'cancel ') {
                  return
                } else if (action == 'confirm') {
                  this.API.userManage
                    .resetPassword({ id: row.id })
                    .then((res) => {
                      // console.log(res)
                      if (res.code === 1) {
                        this.getList()
                        this.$alertFn.success(`密码重置成功 ！`)
                      } else {
                        this.$alertFn.error(`密码重置失败，请稍后再试 ！`)
                      }
                    })
                    .catch((e) => {
                      // console.log(e)
                      // this.$alertFn.error(`密码重置失败，请稍后再试 ！`)
                    })
                }
              },
            }
          )
          return
        case 'selection':
          this.selection = [...selection]
          return
        case 'start':
          text = '启用'
          break
        case 'stop':
          text = '禁用'
          break

        default:
          return
      }
      this.$confirmFn(
        `您确定要${text}用户<span class='light'>${row.userName}(${row.loginName})</span>吗？`,
        '提示',
        {
          callback: (action, instance) => {
            // console.log(method, row)
            if (action == 'cancel ') {
              return
            } else if (action == 'confirm') {
              // console.log(row.id)
              this.updateStatus({
                ids: row.id.toString(),
                status: text === '启用' ? '1' : '0',
              })
            }
          },
        }
      )
    },
    // formConfirm(data) {
    //   // console.log(data)
    //   if (this.editId) {
    //     this.editFormConfirm(data)
    //   } else {
    //     this.addFormConfirm(data)
    //   }
    // },
    // addFormConfirm(data) {
    //   //添加
    //   // console.log(data)
    //   this.API.userManage
    //     .addUser(data)
    //     .then((res) => {
    //       // console.log(res)
    //       if (res.code == '1') {
    //         // this.showForm = false
    //         this.$refs.userForm.ajaxIng = false
    //         this.$alertFn.success('添加用户成功')
    //         this.resetForm()
    //       } else {
    //         this.$refs.userForm.ajaxIng = false
    //       }
    //     })
    //     .catch((error) => {
    //       // console.log(error)
    //       this.$refs.userForm.ajaxIng = false
    //     })
    // },
    // editFormConfirm(data) {
    //   //修改
    //   // console.log(data)
    //   let params = {
    //     ...data,
    //     id: this.editId,
    //   }
    //   this.API.userManage
    //     .updateUser(params)
    //     .then((res) => {
    //       if (res.code == '1') {
    //         // this.showForm = false
    //         this.$refs.userForm.ajaxIng = false
    //         this.$alertFn.success('修改用户成功')
    //         this.resetForm()
    //       } else {
    //         this.$refs.userForm.ajaxIng = false
    //       }
    //     })
    //     .catch((error) => {
    //       this.$refs.userForm.ajaxIng = false
    //     })
    // },
    roleConfirm(data) {
      let param = {
        rodeId: data.roleId.join(','),
      }
      if (typeof this.userId == 'object') {
        param.userId = this.userId.map((v) => v.id).join(',')
      } else {
        param.userId = this.userId
      }
      this.API.userManage
        .dispatchRole(param)
        .then((res) => {
          // console.log(res)
          if (res.code === 1) {
            this.showRole = false
            this.$refs.userRole.ajaxIng = false
            this.getList()
            this.$alertFn.success(`分配角色成功 ！`)
          } else {
            this.$refs.userRole.ajaxIng = false
          }
        })
        .catch((e) => {
          this.$refs.userRole.ajaxIng = false
        })
      // console.log(data)
    },
    updateStatus(param) {
      this.API.userManage
        .updateStatus(param)
        .then((res) => {
          // console.log(res)
          if (res.code === 1) {
            this.getList()
            this.$alertFn.success(`切换用户状态成功 ！`)
          } else {
            this.$alertFn.error(`切换用户状态失败，请稍后再试 ！`)
          }
        })
        .catch((e) => {
          // this.$alertFn.error(`切换用户状态失败，请稍后再试 ！`)
        })
    },
    exportUser() {
      //导出
      let params = {
        ...this.searchRes,
      }
      this.API.userManage
        .exportUser(params)
        .then((res) => {
          // console.log(res)
          if (res.data) {
            // window.location.href=`${grobalbaseUrl.baseUrl}/download/${res.data}/操作日志`;
            downloadFile(
              `${grobalbaseUrl.baseUrl}/download/${res.data}/导出用户`,
              null,
              'url'
            )
          } else {
            this.$alertFn.error('导出失败')
          }
        })
        .catch((e) => {
          // this.$alertFn.error('导出失败')
        })
    },
    downloadExcel() {
      //模板下载
      // downloadFile(
      //   `${grobalbaseUrl.baseUrl}/TSysUser/downloadExcel`,
      //   null,
      //   'url'
      // )
      this.API.userManage.template().then((res) => {
        downloadFile(res.data, '用户导入模板.xlsx', 'excel')
      })

      // this.API.logManage
      //   .exportOperation({})
      //   .then((res) => {
      //     console.log(res.data)
      //     if (res.data) {
      //       console.log(res.data)
      //       downloadFile(
      //         `${grobalbaseUrl.baseUrl}/download/用户导入模板`,
      //         null,
      //         'url'
      //       )
      //     } else {
      //       this.$alertFn.error('导出失败')
      //     }
      //   })
      //   .catch((e) => {
      //     // this.$alertFn.error('导出失败')
      //   })
    },
    beforeUploadFile(file) {
      // console.log(file)
      const isEXCEL =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isEXCEL) {
        this.$alertFn.error('只能导入 excel文件!')
      }
      return isEXCEL
    },
    uploadFile(data) {
      // console.log(data)
      // let vueObj = this;
      let file = data.file
      // console.log(file)
      // const formData = new FormData()
      // formData.append('file', file)
      // console.log(formData)
      this.API.userManage.importExcel({ uploadFile: file }).then((res) => {
        if (res.code == '1') {
          this.$message.success('上传成功')
          this.resetForm()
        }
      })
    },
    getBase() {
      this.API.roleManage.findList().then((res) => {
        if (res.code == '1') {
          this.dictionary.roleList = res.data
        }
      })
      this.API.organization
        .pageList({ pageNum: 1, pageSize: 999999 })
        .then((res) => {
          if (res.data) {
            this.treeArr = res.data.records || []
          }
          // console.log(this.tableData)
        })
        .catch((err) => {})
    },
  },
  created() {},
  activated() {
    this.getBase()
    this.$store.state.keep
      ? this.getList()
      : (this.$store.commit('keepFn', true), this.resetForm())
  },
  mounted() {},
  destroyed() {},
}
</script>
<style scoped>
.upload {
  display: inline-block;
  vertical-align: top;
}
</style>
